//
//  TimerTool.swift
//  TravelForUser
//
//  Created by Rowling on 2020/8/28.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit

public protocol ZMTimerToolDelegate : NSObjectProtocol  {
    func timerGo(time : TimeInterval)
}

class ZMTimerTool {
    static public let shared = ZMTimerTool()
    let disposeBag = DisposeBag()
    var time : TimeInterval = 0
    public let timerGoSubject = PublishSubject<TimeInterval>()
    private init(){
        timer.subscribe { [weak self] (e) in
            guard let self = self else {return}
            DispatchQueue.main.async {
               for bj in self.delegateArray {
                 if let bjDelegate = bj.delegate  {
                    bj.time += 0.01
                    if Int(bj.time * 100) % 100 == 0 {
                        bjDelegate.timerGo(time: bj.time)
                    }
                 }
               }
              self.time += 0.01
                if Int(self.time * 100) % 100 == 0 {
                    self.timerGoSubject.onNext(self.time)
               }
           }
        }.disposed(by: disposeBag)
    }
    private let timer = Observable<Int>.timer(.seconds(0), period: .milliseconds(10), scheduler: MainScheduler.instance)

    private var delegateArray = [BridgeObjc]()
    
    public func addDelegete(delegate : ZMTimerToolDelegate) {
        for bj in delegateArray {
            if let bjdelegate = bj.delegate , bjdelegate.isEqual(delegate)  {
                return
            }
        }
        let bj = BridgeObjc()
        bj.delegate = delegate
        delegateArray.append(bj)
    }
    
    public func removeDelegate(delegate : ZMTimerToolDelegate) {
        var newDelegateArray = [BridgeObjc]()
        for bj in delegateArray {
            if bj.delegate == nil || bj.delegate!.isEqual(delegate) {
               
            } else {
                newDelegateArray.append(bj)
            }
        }
        delegateArray = newDelegateArray
    }

    
}

class BridgeObjc : NSObject {
    weak var delegate : ZMTimerToolDelegate?
    public var time : TimeInterval = 0
}
